package org.blog.helper;

import java.io.IOException;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;

public class JsonHttpMessageConverter extends MappingJacksonHttpMessageConverter {

	private static Logger logger = LoggerFactory.getLogger(JsonHttpMessageConverter.class);

	@Override
	protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException,
			HttpMessageNotReadableException {
		Object object = super.readInternal(clazz, inputMessage);
		logger.info("request body: {}", JsonMapper.toJsonString(object));
		return object;
	}

	@Override
	protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException,
			HttpMessageNotWritableException {
		logger.info("response body: {}", JsonMapper.toJsonString(object));
		super.writeInternal(object, outputMessage);
	}

	/**
	 * 对mapper进行初始化
	 */
	public void initMapper() {
		ObjectMapper mapper = getObjectMapper();
		// 不序列化空元素，包括null,""以及空Collection和Array
		mapper.setSerializationInclusion(Inclusion.NON_EMPTY);

		// 設定是否使用Enum的toString函數來讀寫Enum,
		// 為False時時使用Enum的name()函數來讀寫Enum, 默認為False.
		mapper.enable(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING);
		mapper.enable(DeserializationConfig.Feature.READ_ENUMS_USING_TO_STRING);
		logger.info("----------------jackson mappper initialize success.-------------");
	}
}
